<?php

namespace App\Tables;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Categories extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'name', 'code', 'parent_id', 'sort'
    ];

    /**
     * 获取某类目的直接子分类
     * @param $id
     * @return mixed
     */
    public function getSons($id)
    {
        return $this->withTrashed()->where('pid', $id)->get();
    }

    /**
     * 获取某个类目下的所有子类目
     * @param $id
     * @param int $level
     * @return array
     */
    public function getAllSons($id, $level = 1)
    {
        $sons = array();

        $categories = $this->withTrashed()->get();

        foreach ($categories as $item) {
            if ($item->parent_id == $id) {
                $item->level = $level;
                $item->disabled = $item->trashed();

                $children = $this->getAllSons($item->id, $level++);
                if (!empty($children)) {
                    $item->children = $this->getAllSons($item->id, $level++);
                }

                $sons[] = $item;
            }
        }

        return $sons;
    }

    /**
     * 获取某个类目的父级类目
     * @param $id
     * @return array
     */
    public function getParents($id)
    {
        $tree = array();

        $categories = $this->withTrashed()->get();
        foreach ($categories as $item) {
            if ($item->id == $id) {
                if ($item->parent_id > 0) {
                    $tree = array_merge($tree, $this->getParents($item->parent_id));
                }
                $item->disabled = $item->trashed();
                $tree[] = $item;
                break;
            }
        }

        return $tree;
    }
}
